package Opgave9_3;

import java.sql.*;

public class DbDataAccessObject {

	public static void savePerson(Person person) throws SQLException, ClassNotFoundException {
		Class.forName("org.apache.derby.jdbc.EmbeddedDriver");
		Connection con = null;
		PreparedStatement stmt = null;
		try{
			con = DriverManager.getConnection("jdbc:derby:PersonDB;create=true");			
			String sql = "INSERT INTO PERSON VALUES(?, ?, ?)";
			 
			stmt = con.prepareStatement(sql);
			stmt.setInt(1, person.getId());
			stmt.setString(2, person.getFirstName());
			stmt.setString(3, person.getLastName());
			stmt.executeUpdate();
		}
		catch(SQLException e){
			System.out.println(e);
		}
	}


	public static Person loadPerson(int id) throws SQLException, ClassNotFoundException {
		Class.forName("org.apache.derby.jdbc.EmbeddedDriver");
		Connection con = null;
		PreparedStatement stmt = null;
		String fN = null;
		String lN = null;
		try{
			con = DriverManager.getConnection("jdbc:derby:PersonDB;create=true");
			String sql = "SELECT FIRST_NAME, LAST_NAME FROM PERSON WHERE PERSON_PK=?";
			stmt = con.prepareStatement(sql);
			stmt.setInt(1, id);
			ResultSet rs = stmt.executeQuery();
			while(rs.next()){
				fN = (rs.getString("FIRST_NAME"));
				lN = (rs.getString("LAST_NAME"));
			}
			Person person = new Person(id, fN, lN);
			return person;
		}
		catch(SQLException e){
			System.out.println(e);
		}
		return null;

	}
}
